﻿using System;
using System.Diagnostics;
using System.IO;
using AutoBuild.Core;
using AutoBuild.Core.Configuration;
using AutoBuild.Core.Framework;
using AutoBuild.Runner.NAntRunner;
using Machine.Specifications;
using Rhino.Mocks;

namespace AutoBuild.Specs.Core
{

    [Subject(typeof(NAntBuildRunner))]
    public class when_running_build : NAntBuildRunnerSpecs
    {
        protected static bool buildStartedEventWasRaised;
        protected static bool buildCompletedEventWasRaised;
        private static string nantPath = "c:\\foo\\nant.exe";

        Establish context = () =>
        {
            Subject.BuildStarted += (sender, e) => buildStartedEventWasRaised = true;
            Subject.BuildCompleted += (sender, e) => buildCompletedEventWasRaised = true;
            pathResolver.Expect(p => p.Resolve(((NAntBuildRunnerOptions)autoBuildArguments.RunnerArgument).NAntExePath)).Return(nantPath);
        };

        Because of = () =>
            Subject.RunBuild(autoBuildArguments);

        It should_resolve_nant_exe_path = () =>
            pathResolver.WasCalled(p => p.Resolve(((NAntBuildRunnerOptions)autoBuildArguments.RunnerArgument).NAntExePath));

        It should_raise_build_started_event = () =>
            buildStartedEventWasRaised.ShouldBeTrue();

        It should_raise_build_completed_event = () =>
            buildCompletedEventWasRaised.ShouldBeTrue();

        It should_not_send_error_message_to_console = () => console.WasNotCalled(l => l.Error(null, null),
                                                                                         c => c.IgnoreArguments());

        It schould_call_execute_on_the_process_executor =
            () =>
            processExecutor.WasCalled(
                p => p.Execute(Arg<ProcessStartInfo>.Matches(a => a.FileName == nantPath)));

    }


    public abstract class NAntBuildRunnerSpecs : Specification<NAntBuildRunner>
    {
        protected static AutoBuildArguments autoBuildArguments;
        
        protected static IPathResolver pathResolver;
        protected static IProcessExecutor processExecutor;
        protected static IConsole console;

        Establish context = () =>
        {
            autoBuildArguments = new AutoBuildArguments
                {
                    BuildFile = "test.build",
                    WatchFolder = "somewatchdirectory",
                    RunnerArgument = new NAntBuildRunnerOptions { NAntExePath = "nant.exe" } 
                   
                };

            processExecutor = Mock<IProcessExecutor>();
            pathResolver = Mock<IPathResolver>();
            console = Mock<IConsole>();
            Subject = new NAntBuildRunner(pathResolver, console, processExecutor) { CreateNoWindow = true};
            
        };
    }
}